#include "httpmgr.h"
#include <QNetworkReply>

HttpMgr::~HttpMgr()
{

}

HttpMgr::HttpMgr()
{
    connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slots_http_finish);
}

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules modules){
    QByteArray data = QJsonDocument(json).toJson();
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(data.length()));
    std::shared_ptr<HttpMgr>self = shared_from_this();
    QNetworkReply* reply = _manager.post(request,data);//发送请求
    QObject::connect(reply,&QNetworkReply::finished,[self,reply,req_id,modules](){
        //处理错误情况
        if(reply->error()!=QNetworkReply::NoError){
            qDebug()<<reply->errorString();
            //发信号通知完成
            emit self->sig_http_finish(req_id,"",ErrorCodes::ERR_NETWORK,modules);
            reply->deleteLater();
            return;
        }
        //如果没有错误发生
        QString res = reply->readAll();
        //发送信号通知完成
        emit self->sig_http_finish(req_id,res,ErrorCodes::SUCCESS,modules);
        reply->deleteLater();
        return;
    });
}

void HttpMgr::slots_http_finish(ReqId id, QString res, ErrorCodes err, Modules modules)
{
    //如果是注册模块
    if(modules == Modules::REGISTERMOD){
        emit sig_reg_mod_finish(id,res,err);//发送信号让注册模块处理
    }else if(modules == Modules::RESETMOD){
        emit sig_reset_mod_finish(id,res,err);//发送信号让重置密码模块处理
    }else if(modules == Modules::LOGINMOD){
        emit sig_login_mod_finish(id,res,err);//发送信号让登录模块处理
    }
}
